<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
		
	if (!isset($_POST['is_submitted'])) {
		$_POST['is_submitted'] = '';
	}
	if (!isset($error_message)) {
		$error_message = '';
	}	
	
	
	if($_POST["redirect"] || $_SESSION['redirect'] ){
		if($_POST["redirect"]) $redirect = $_POST["redirect"];
		if($_SESSION['redirect']){ 
			$redirect = $_SESSION['redirect'];
			unset($_SESSION['redirect']);
		}
	}else{
		   $redirect = $_SERVER['HTTP_REFERER'];	
		 }			
	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	$sql = 'SELECT 
						lang_id,
						Name,
						code
						
					FROM
						language
					WHERE
						published
					
					';
	$result_lang = query($sql);
	
	while ($row_lang = mysql_fetch_object($result_lang)) {
	
	
				$em = $row_lang->lang_id;
				eval('$name =  $_POST[\'title_'.$em.'\'];');
				
				

	if (!$name)  $error_message .= 'Не е въведено име на '.$row_lang->Name.'<br/>';
	}
	
	
	
	
	
	require "../../include/image_allowed_type.inc.php";
		
	if (!$_FILES['image_th']['name']) $error_message .= 'Не е избрана снимка<br/>';
	if(!array_search($_FILES['image_th']['type'], $allowed_types) && $_FILES['image_th']['name']) $error_message .= 'Форматът на снимката не е позволен<br/>';
	/*if ($_FILES['image_th']['name'])
	{
		$size = getimagesize($_FILES['image_th']['tmp_name']);
		if ($size[0]!== CAT_THUMB_WIDTH) $error_message .= 'Широчината на снимката не е точно CAT_THUMB_WIDTH пиксела!<br/>';
		if ($size[1]!== CAT_THUMB_HEIGHT) $error_message .= 'Височината на снимката не е точно CAT_THUMB_HEIGHT пиксела!<br/>';
	}*/
	
	
	//ОК
    if(!$error_message) {
		
	
		
		$sql = 'SELECT MAX(order_number)+1 AS order_number FROM photographers';
		$row_number = mysql_fetch_assoc(query($sql));
		
		//Създаваме проекта
		$sql = 'INSERT INTO photographers
				  (sef_url, published, order_number)
				VALUES
				  (\''.escape($_POST['sef_url']).'\', \''.intval($_POST['published']).'\', \''.$row_number['order_number'].'\')
				  ';
		query($sql);
		$id = mysql_insert_id();
		$sql = 'SELECT lang_id,Name,code
				FROM
				language
				WHERE
				published
					';
		$result_lang = query($sql);
		
		while ($row_lang = mysql_fetch_object($result_lang)) {
			
				$em = $row_lang->lang_id;
				eval('$name =  $_POST[\'title_'.$em.'\'];');
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				
			
			$sql = "INSERT INTO photographers_description
				  (photographers_id, lang_id, title, description)
				VALUES
				  ('".$id."','".$em."', '".escape($name)."', '".escape($description)."')";
				 
		query($sql);
		}
		
		
		// снимка
		$upload_path = "../photographers/";
		if (is_uploaded_file($_FILES['image_th']['tmp_name'])) {
			$tmp_file = $_FILES['image_th']['tmp_name'];
			$exp = explode('.',$_FILES['image_th']['name']);
			$img_type = strtolower(end($exp));
			
			$new_name = "photographer_".$id.".".$img_type;
			if(copy($tmp_file, $upload_path.$new_name)) {
				
				$sql = "UPDATE photographers
						SET
				image = '$new_name'
						WHERE photographers_id = '$id'";
				query($sql);
				
			} else{
				
				$_SESSION['message'] .= 'Грешка при качване на снимка. ';
				
			}
		}
		
		
		
		$_SESSION['message'] .= 'Редакцията е записана успешно!';
         if($_POST["redirectForm"]){
           redirect($_POST["redirectForm"]);
		}else{
			$_SESSION['redirect'] = $redirect;
		   redirect('photographers_edit.php?photographers_id='.$id);
		}
    }

}
  	
	
	head_admin("Добавяне на фотограф");
?>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>js/calendarDateInput.js"></script>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	language : "en", 
	mode : "exact",
    elements : "body1,body2,body3,body4,body5",
	theme : "advanced",
	relative_urls : false,
	height : 300,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,

	// Drop lists for link/image/media/template dialogs
	//template_external_list_url : "js/template_list.js",
	//external_link_list_url : "js/link_list.php",
	//media_external_list_url : "js/media_list.js",
	//external_image_list_url : "js/blog_image_list.php"
	
});
</script>
<?php if ($error_message) { ?>
        <div class="message red">
            <h3>Грешка!</h3>
             <?=$error_message?>
        </div>
<?php } ?>

<?php if ($_SESSION['message']) { ?>
			<div class="message green">
				
				<?=$_SESSION['message']?>
			</div>
			<?php 
			unset($_SESSION['message']);
			} ?>
            
            
<div class="topbuttons"> <a href="<?=$redirect?>">Обратно</a> </div>
<h3>Добавяне на фотограф</h3>
<form id="photographers_new_form_id"action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
	<input type="hidden" name="is_submitted" value="1" />
	<input type="hidden" name="redirect" value="<?=$redirect?>" />
	<input id="redirectForm" type="hidden" name="redirectForm" value="" />
  
  
  <dt><label class="required">Линк към страницата:</label>
    <?=HTML_BASE?><input id="sef_url"  name="sef_url" type="text" value="<?=$_POST["sef_url"]?>" />
 	</dt>
  
  
  <!-- Tabs beginning-->
	<div id="tabs">
		<ul id="tabs-ui"></ul>
                            
	<?php 
			
			$sql = 'SELECT 
						lang_id,
						Name,
						code
						
					FROM
						language
					WHERE
						published
					
					';
			$result = query($sql);
			
			$i=0;
			$tabs="";
			while ($row_lang = mysql_fetch_object($result)) {
				
			
				$em = $row_lang->lang_id;
				$tabs.='<li><a href="'.$_SERVER['PHP_SELF'].'#tabs-'.$em.'">'.$row_lang->Name.'</a></li>';
				
				eval('$name =  $_POST[\'title_'.$em.'\'];');
				eval('$description =  $_POST[\'description_'.$em.'\'];');
				eval('$meta_k =  $_POST[\'meta_key_'.$em.'\'];');
				eval('$meta_d =  $_POST[\'meta_description_'.$em.'\'];');
				
							  
			?>
           <div id="tabs-<?=$em?>">
              <dl class="clearfix">
                <h3>Данни на  <?=$row_lang->Name?> </h3>
                <dt>
                  <label class="required">Заглавие на  <?=$row_lang->Name?> </label>
                </dt>
                <dd>
                  <input class="inputbox w500" id="title_<?=$row_lang->lang_id?>" name="title_<?=$row_lang->lang_id?>" type="text" value="<?=$name?>" >
                </dd>
                <dt>
                  <label>Описание на  <?=$row_lang->Name?></label>
                </dt>
                <dd>
                  <textarea id="body<?=$row_lang->lang_id?>"  class="inputbox" style="width:100%" name="description_<?=$row_lang->lang_id?>" rows="16"><?=sth($description)?></textarea>
                </dd>
                
              </dl>
           </div>
		<?php
          	 $i++;     
            }
        ?>
                
  </div>             
  <dl>             
     <dt>         
    
        <label class="required">Портрет на фотографа (
        <?=PHOTOGRAFER_THUMB_WIDTH?>
        на
        <?=PHOTOGRAFER_THUMB_HEIGHT?>
        px)</label>
     </dt>
     <dd>
         <input class="inputbox w500" name="image_th" type="file" />
     </dd>
         <input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
               Публикуван
                </label>
     </dd>
  </dl>
             
</form>          


<script>
	$(document).ready(function() {
	
    	// Tabs
		$("#tabs-ui").html('<?=$tabs?>');
		$( "#tabs" ).tabs();	
	
	});
</script>
 
<?php
	controls($redirect, "#photographers_new_form_id");
	foot_admin(); 
?>
